package com.icoolkj.web.biz.system;

import com.icoolkj.common.constant.CacheConstants;
import com.icoolkj.common.constant.Constants;
import com.icoolkj.common.constant.SysConstants;
import com.icoolkj.common.core.domain.entity.SysDept;
import com.icoolkj.common.core.domain.entity.SysDomain;
import com.icoolkj.common.core.domain.entity.SysRegister;
import com.icoolkj.common.core.domain.entity.SysUser;
import com.icoolkj.common.core.domain.model.CompRegisterBody;
import com.icoolkj.common.core.redis.RedisCache;
import com.icoolkj.common.exception.user.CaptchaException;
import com.icoolkj.common.exception.user.CaptchaExpireException;
import com.icoolkj.common.security.keys.RsaKeyPairHolder;
import com.icoolkj.common.utils.DateUtils;
import com.icoolkj.common.utils.MessageUtils;
import com.icoolkj.common.utils.SecurityUtils;
import com.icoolkj.common.utils.StringUtils;
import com.icoolkj.common.utils.uuid.IdWorker;
import com.icoolkj.company.domain.DcCompBasic;
import com.icoolkj.company.service.IDcCompBasicService;
import com.icoolkj.framework.manager.AsyncManager;
import com.icoolkj.framework.manager.factory.AsyncFactory;
import com.icoolkj.system.domain.SysUserRole;
import com.icoolkj.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 注册 biz
 *
 * @author icoolkj
 */
@Service
public class SysRegisterBiz
{
    @Autowired
    private IDcCompBasicService dcCompBasicService;

    @Autowired
    private ISysRegisterService sysRegisterService;

    @Autowired
    private ISysDomainService sysDomainService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;



    @Transactional(rollbackFor = Exception.class)
    public String compRegister(CompRegisterBody registerBody) {
        try {
            SysRegister sysRegister = new SysRegister();
            sysRegister.setRegisterType(registerBody.getRegisterType());
            sysRegister.setRegisterAccount(registerBody.getRegisterAccount());
            sysRegister.setRegisterNickName(registerBody.getRegisterNickName());
            sysRegister.setRegisterLxr(registerBody.getRegisterLxr());
            sysRegister.setRegisterLxrPhone(registerBody.getRegisterLxrPhone());
            sysRegister.setRegisterLxrEmail(registerBody.getRegisterLxrEmail());
            String password = RsaKeyPairHolder.decryptByPrivateKey(registerBody.getRegisterPassword());
            sysRegister.setRegisterPassword(SecurityUtils.encryptPassword(password));
            sysRegisterService.insertSysRegister(sysRegister);
            compRegisterPass(sysRegister, true);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(registerBody.getRegisterAccount(), "", Constants.REGISTER, MessageUtils.message("user.register.success")));
            return "";
        } catch (Exception e){
            return "注册失败,请联系系统管理人员！";
        }
    }

    /**
     * 企业注册（审核通过产生相应账号信息）
     *
     * @param sysRegister 企业注册信息
     * @param isTimedTask 是否定时任务处理【定时任务时，创建人默认】
     * @return 结果
     */
    public void compRegisterPass(SysRegister sysRegister, boolean isTimedTask) {
        if (isTimedTask) {
            sysRegister.setAuditBy("timedTask");
            sysRegister.setAuditTime(DateUtils.getNowDate());
            sysRegister.setAuditIdea("系统默认通过。");
        } else {
            sysRegister.setAuditBy(SecurityUtils.getLoginUser().getUser().getUserName());
        }
        sysRegister.setRegisterStatus("2"); //账号注册状态（1代表申请中|2代表审核通过|3代表审核不通过）
        sysRegisterService.updateSysRegister(sysRegister);
        DcCompBasic dcCompBasic = new DcCompBasic();
        dcCompBasic.setCompBasicId(IdWorker.nextId().toString());
        dcCompBasic.setCompName(sysRegister.getRegisterNickName());
        dcCompBasic.setCompCreditCode(sysRegister.getRegisterAccount());
        dcCompBasic.setCompLxr(sysRegister.getRegisterLxr());
        dcCompBasic.setCompLxrPhone(sysRegister.getRegisterLxrPhone());
        dcCompBasic.setCompLxrEmail(sysRegister.getRegisterLxrEmail());
        dcCompBasic.setCompArea(SysConstants.AREA_00);
        dcCompBasic.setCreateBy(sysRegister.getAuditBy());
        dcCompBasic.setCreateTime(DateUtils.getNowDate());
        dcCompBasicService.createDcCompBasic(dcCompBasic);
        SysDomain compDomain = sysDomainService.createCompDomainAccount(dcCompBasic);
        SysDept compDept = sysDeptService.createCompDefaultDept(compDomain);
        SysUser user = sysUserService.createCompDefaultUser(compDomain, compDept, sysRegister.getRegisterPassword());
        //添加角色
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(SysConstants.ROLE_COMP);
        sysRoleService.batchUserRole(Arrays.asList(userRole));
    }


}
